package com.cwnu.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cwnu.entity.User;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: mall
 * @Titile: JWTUtil
 * @Author: Lucky
 * @Description: 操作token的工具类
 */
public class JWTUtil {
    //有效期为30分钟
    private static final long EXPIRATION_TIME = 7*24*60 * 60 * 1000; //默认一周
    //服务端的秘钥，切记保密，而且注意周期更换
    private static final String SECRET = "http://www.cwnu.edu.cn";

    /**
     * 生成token
     * @param user
     * @return
     */
    public static String generateToken(User user){
        Map<String,Object> map = new HashMap<>();
        map.put("userId",user.getUserId());
        //hash256+密钥进行加密
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        //租约到期时间
        Long expireTime = new Date().getTime() + EXPIRATION_TIME;
        SimpleDateFormat sdf = new SimpleDateFormat();
        Calendar calendar = Calendar.getInstance();
        //设置时间
        calendar.setTimeInMillis(expireTime);
        Date time = calendar.getTime();
        //生成token
        String token = JWT.create()
                .withPayload(map) //负载：用户信息
                .withExpiresAt(time) //过期时间
                .sign(algorithm); //算法
        return token;
    }

    /**
     * 解析token：校验token的合法性
     * @param token
     */
    public static Map<String,Claim> parseToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWTVerifier verifier = JWT.require(algorithm)
                .build(); //Reusable verifier instance
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        return claims;
    }

    /**
     * 获取token中的信息
     * @param token
     * @return
     */
    public static User getUserInfo(String token){
        Map<String, Claim> map = parseToken(token);
        Claim claim = map.get("userId");
        Integer integer = claim.asInt();
        User user = new User();
        user.setUserId(integer.intValue());
        return user;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setUserId(1002);
        String token = generateToken(user);
        System.out.println(token);
    }

}
